<template>
  <div class="esign-container">
    <vue-esign
      ref="esign"
      :width="800"
      :height="300"
      :isCrop="isCrop"
      :lineWidth="lineWidth"
      :lineColor="lineColor"
      :isClearBgColor="isClearBgColor"
      v-model:bgColor="bgColor"
    />
    <el-button @click="handleReset">清空画板</el-button>
    <el-button @click="handleGenerate">生成图片</el-button>
  </div>
</template>
<script setup>
import vueEsign from "vue-esign";
import { ref } from "vue";

const esign = ref(null);
const lineWidth = ref(6); //画笔粗细
const lineColor = ref("#000000"); //画笔颜色
const bgColor = ref("#ffffff"); //画布背景颜色
const isCrop = ref(false); //是否裁剪
const resultImg = ref("");
const isClearBgColor = ref(false); //是否清除画布背景色

const handleReset = () => {
  esign.value.reset();
};

const handleGenerate = () => {
  esign.value
    .generate()
    .then((res) => {
      console.log("res", res);
      resultImg.value = res;
      const blob = base64ToBlob(res, "file");
      const url = URL.createObjectURL(blob);

      // 创建一个链接
      const link = document.createElement("a");
      link.href = url;
      link.download = "签名.png"; // 文件名可以根据需要修改
      document.body.appendChild(link);

      // 模拟点击链接触发下载
      link.click();

      // 清理资源
      URL.revokeObjectURL(url);
      document.body.removeChild(link);
    })
    .catch((err) => {
      console.log("err", err);
    });
};

/**
 * base64转blob
 * @param urlData
 * @param type
 * @returns {module:buffer.Blob}
 */
const base64ToBlob = (dataurl, fileName = "file") => {
  const arr = dataurl.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const suffix = mime.split("/")[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  var u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], `${fileName}.${suffix}`, { type: mime });
};
</script>
<style scoped lang="scss">
.esign-container {
  position: relative;
  padding: 20px;
}
</style>
